Skip to content

fix loss metric when enable sp#59

Merged
meichangsu1 merged 6 commits intodevfrom
seq_unitest_ljl_fix
Feb 13, 2026
Merged

fix loss metric when enable sp#59
meichangsu1 merged 6 commits intodevfrom
seq_unitest_ljl_fix

Conversation

@meichangsu1
Copy link
Copy Markdown
Collaborator

No description provided.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @meichangsu1, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request resolves an inaccuracy in loss metric calculation when Sequence Parallelism is active, particularly when combined with FSDP. The core solution involves introducing a compensation mechanism for FSDP's averaging behavior and refining the loss reduction process through custom autograd functions. These changes ensure that gradients are scaled correctly and the reported loss accurately reflects the model's performance under distributed training configurations.

Highlights

  • Loss Metric Correction for Sequence Parallelism (SP): The pull request addresses an issue where the loss metric was incorrectly calculated when Sequence Parallelism (SP) was enabled, especially in conjunction with FSDP (Fully Sharded Data Parallel).
  • Gradient Scaling in Backward Pass: A scaling factor is now applied to gradients in the backward pass for sequence parallel operations to ensure correct gradient magnitudes when sequence dimension is replicated across SP ranks.
  • Refactored Loss Reduction with Custom Autograd Functions: The reduce_loss function within SequenceParallelStrategy has been refactored to utilize custom torch.autograd.Function classes. This provides more precise control over gradient flow and compensation during mean and sum loss reductions, particularly when FSDP averaging is involved.
  • Introduction of compensate_fsdp_avg Configuration: A new configuration option, compensate_fsdp_avg, has been added to SequenceParallelConfig. This flag, when enabled, triggers compensation for FSDP's averaging behavior to maintain correct loss scaling.
  • Mathematical Derivation in README: The README.md file has been updated with mathematical derivations explaining the necessity and logic behind the loss compensation mechanism when SP is used with FSDP.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • README.md
    • Added mathematical derivations explaining loss compensation for sequence parallelism with FSDP.
  • src/twinkle/model/transformers/strategy/sequence_parallel.py
    • Applied a scaling factor to gradients in the backward pass to compensate for sequence dimension replication in sequence parallel operations.
    • Corrected the label masking logic in pad_and_split_inputs to properly handle boundary conditions.
    • Introduced compensate_fsdp_avg as a new configuration option in SequenceParallelConfig.
    • Refactored the reduce_loss method to use _ReduceSequenceParallelLoss and _ReduceSequenceParallelSum custom torch.autograd.Function classes for more accurate mean and sum loss reduction with gradient compensation.
  • src/twinkle/model/transformers/transformers.py
    • Conditionally set the compensate_fsdp_avg flag in the SequenceParallelStrategy configuration based on the presence of NativeFSDPStrategy or AccelerateStrategy and relevant device mesh properties.
    • Streamlined the logic for setting the loss_reduction parameter in the sequence parallel strategy.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request fixes an issue with loss and gradient scaling when sequence parallelism (SP) is enabled with FSDP/DDP. The changes introduce a compensation factor in the backward pass to correct for the extra averaging performed by FSDP across SP ranks. This is controlled by a new compensate_fsdp_avg flag. The implementation of loss reduction has been refactored to use torch.autograd.Function for cleaner custom gradient computation.

My review identifies a critical issue in the new implementation of _ReduceSequenceParallelSum which could lead to incorrect gradient scaling, and a medium-severity issue in the README.md documentation. I've provided detailed comments and suggested fixes for both.

…d functions

Replace manual gradient handling with `torch.autograd.Function` subclasses `_ReduceSequenceParallelLoss` and `_ReduceSequenceParallelSum` to compute global loss via autograd-aware all-reduce. This simplifies the logic for both sum and mean reductions, improves gradient correctness, and removes the need for separate metric scaling when `world_size > 1`.
Add `compensate_fsdp_avg` config flag to adjust loss reduction when sequence parallel (SP) is combined with FSDP or accelerate DDP/FSDP. This prevents gradient magnitude from being incorrectly scaled down by an extra factor of SP world size during data-parallel averaging.

- In `GatherLoss` backward, scale gradients by SP world size before splitting, so downstream FSDP averaging does not shrink this path.
- In `SequenceParallelStrategy.reduce_loss`, apply a compensation factor (ulysses_size) when `compensate_fsdp_avg` is enabled.
- Automatically set `compensate_fsdp_avg=True` in `TransformersModel` when using NativeFSDPStrategy or AccelerateStrategy with both SP and data parallelism active.
- Add 'kernels' as an optional dependency group in pyproject.toml
- Refactor CI container test script to use a reusable installation function
- Install twinkle with kernels in both debug and release modes for consistency
- Improve maintainability by centralizing the installation command
Update `_load_from_hub` function to handle API changes in `select_revision_or_version` and `get_kernel` calls. The changes introduce try-except blocks to catch `TypeError` exceptions, allowing the function to work with both modern keyword-based APIs and older positional argument variants. This ensures compatibility across different versions of the kernels module without breaking existing functionality.
@meichangsu1 meichangsu1 merged commit 905d5fb into dev Feb 13, 2026
2 of 4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant